package com.eric.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eric.product.dao.ProductMapper;
import com.eric.product.entity.Product;
import com.eric.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author:Eric
 * @date:2021/7/7
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reduce(Product product) {
        Product product1 = this.getById(product.getId());
        if (Objects.isNull(product1)) {
            throw new RuntimeException("product not exist");
        }
        long total = product1.getTotal() - product.getTotal();
        if (total < 0) {
            throw new RuntimeException("product is not enough");
        }
        this.updateById(product1.setTotal(total));
    }
}
